package com.example.admin.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;

/**
 * JsonUtil 类提供了一系列用于JSON转换的工具方法。
 */
public class JsonUtil {

    private static ObjectMapper objectMapper;

    /**
     * 将JSON字符串转换为指定类型的对象。
     *
     * @param json JSON字符串
     * @param typeReference 目标类型的TypeReference
     * @return 转换后的对象
     */
    public static <T> T convertJsonToObject(String json, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将对象转换为JSON字符串。
     *
     * @param object 需要转换的对象
     * @return 转换后的JSON字符串
     */
    public static String convertObjectToJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    static {
        // 初始化默认的序列化提供者
        DefaultSerializerProvider.Impl defaultSerializerProvider = new DefaultSerializerProvider.Impl();
        // 创建ObjectMapper实例，并配置其默认的序列化和反序列化设置
        objectMapper = new ObjectMapper((JsonFactory) null, defaultSerializerProvider, (DefaultDeserializationContext) null);
        // 配置ObjectMapper以将空字符串视为null对象
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        // 配置ObjectMapper以在遇到未知属性时不抛出异常
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 配置ObjectMapper以不将浮点数转换为BigDecimal
        objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, false);
        // 设置ObjectMapper以在序列化时忽略值为null的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

}
